<template>
    <div class="student-manage">
      <div class="actions">
            <el-input v-model="query.keyword" placeholder="搜索学生姓名或学号" style="width: 300px; margin-left: 10px" clearable
                @change="handleSearch">
                <template #suffix>
                    <el-icon>
                        <Search />
                    </el-icon>
                </template>
            </el-input>
            <el-select v-model="query.grade" placeholder="年级" clearable style="width: 120px; margin-left: 10px" @change="handleSearch">
                <el-option label="一年级" value="一年级" />
                <el-option label="二年级" value="二年级" />
                <el-option label="三年级" value="三年级" />
                <el-option label="四年级" value="四年级" />
                <el-option label="五年级" value="五年级" />
                <el-option label="六年级" value="六年级" />
            </el-select>
            <el-select v-model="query.classNumber" placeholder="班级" clearable style="width: 120px; margin-left: 10px" @change="handleSearch">
                <el-option v-for="item in classList" :key="item.className" :label="item.className" :value="item.className" />
            </el-select>
            <el-select v-model="query.gender" placeholder="性别" clearable style="width: 100px; margin-left: 10px" @change="handleSearch">
                <el-option label="男" :value="1" />
                <el-option label="女" :value="0" />
            </el-select>
        </div>
      <div class="actions">
        <el-button type="primary" @click="showAddDialog">添加学生</el-button>
        <el-button type="success" @click="showUploadDialog">批量导入</el-button>
        <el-button type="warning" @click="handleExport" :loading="exportLoading">导出数据</el-button>
      </div>
        <div class="table-container">
            <el-table :data="studentList" border stripe v-loading="loading" height="500">
                <el-table-column prop="studentId" label="学号" width="120" />
                <el-table-column prop="name" label="姓名" width="120" />
                <el-table-column prop="gender" label="性别" width="80">
                    <template #default="scope">
                        {{ scope.row.gender === 1 ? '男' : '女' }}
                    </template>
                </el-table-column>
              <el-table-column prop="grade" label="年级" width="150" />
                <el-table-column prop="className" label="班级" width="180" />
                <el-table-column prop="createTime" label="创建时间" width="200" />
                <el-table-column label="操作" width="200" fixed="right">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <div class="pagination">
            <el-pagination v-model:current-page="query.page" v-model:page-size="query.size"
                :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <!-- 添加/编辑学生对话框 -->
        <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑学生' : '添加学生'" width="600px">
            <el-form :model="form" label-width="100px" :rules="rules" ref="studentForm">
                <el-form-item label="学号" prop="studentId">
                    <el-input v-model="form.studentId" placeholder="请输入学号" />
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="form.name" placeholder="请输入姓名" />
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                    <el-radio-group v-model="form.gender">
                        <el-radio :label="1">男</el-radio>
                        <el-radio :label="0">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="班级" prop="classId">
                    <el-select v-model="form.classId" placeholder="请选择班级" style="width: 100%">
                        <el-option v-for="item in classList" :key="item.className" :label="item.className" :value="item.className" />
                    </el-select>
                </el-form-item>
                <el-form-item label="年级" prop="grade">
                    <el-input v-model="form.grade" placeholder="请输入年级" />
                </el-form-item>
                <el-form-item v-if="isEdit" label="创建时间">
                    <el-input v-model="form.createTime" disabled />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 批量导入对话框 -->
        <el-dialog v-model="uploadVisible" title="批量导入学生" width="600px">
            <div class="upload-tips">
                <p>请上传Excel（.xlsx）格式的学生信息表。</p>
                <p>表格应包含：学号、姓名、性别、班级、年级等信息。</p>
                <el-link type="primary" @click="downloadTemplate">下载模板</el-link>
            </div>
            <el-upload
                ref="uploadRef"
                v-model:file-list="fileList"
                :auto-upload="false"
                :limit="1"
                :on-exceed="handleExceed"
                :before-upload="beforeUpload"
                accept=".xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                drag
                class="upload-demo"
            >
                <el-icon class="el-icon--upload">
                    <UploadFilled />
                </el-icon>
                <div class="el-upload__text">
                    将文件拖到此处，或<em>点击上传</em>
                </div>
                <template #tip>
                    <div class="el-upload__tip">
                        只能上传Excel（.xlsx）文件，且不超过10MB
                    </div>
                </template>
            </el-upload>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="uploadVisible = false">取 消</el-button>
                    <el-button type="primary" @click="submitUpload" :loading="uploadLoading">
                        开始导入
                    </el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 导入结果对话框 -->
        <el-dialog v-model="resultVisible" title="导入结果" width="800px">
            <div class="result-summary">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-statistic title="总记录数" :value="importResult.total" />
                    </el-col>
                    <el-col :span="8">
                        <el-statistic title="成功导入" :value="importResult.success" />
                    </el-col>
                    <el-col :span="8">
                        <el-statistic title="导入失败" :value="importResult.failed" />
                    </el-col>
                </el-row>
            </div>

            <div v-if="importResult.errors && importResult.errors.length > 0" class="error-details">
                <h4>失败详情：</h4>
                <el-table :data="importResult.errors" border>
                    <el-table-column prop="row" label="行号" width="80" />
                    <el-table-column prop="studentNumber" label="学号" width="120" />
                    <el-table-column prop="studentName" label="姓名" width="100" />
                    <el-table-column prop="error" label="失败原因" show-overflow-tooltip />
                </el-table>
            </div>

            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="resultVisible = false">确 定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 导出对话框 -->
        <el-dialog v-model="exportVisible" title="导出学生数据" width="500px">
            <el-form label-width="100px">
                <el-form-item label="导出范围">
                    <el-radio-group v-model="exportOptions.type">
                        <el-radio label="current">当前页数据</el-radio>
                        <el-radio label="filtered">筛选结果</el-radio>
                        <el-radio label="all">全部数据</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="导出格式">
                    <el-radio-group v-model="exportOptions.format">
                        <el-radio label="xlsx">Excel格式</el-radio>
                        <el-radio label="csv">CSV格式</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="包含字段">
                    <el-checkbox-group v-model="exportOptions.fields">
                        <el-checkbox label="studentNumber">学号</el-checkbox>
                        <el-checkbox label="studentName">姓名</el-checkbox>
                        <el-checkbox label="gender">性别</el-checkbox>
                        <el-checkbox label="grade">年级</el-checkbox>
                      <el-checkbox label="className">班级</el-checkbox>
                        <el-checkbox label="createTime">创建时间</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="exportVisible = false">取 消</el-button>
                    <el-button type="primary" @click="confirmExport" :loading="exportLoading">
                        开始导出
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { Search, UploadFilled } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import studentApi from '@/api/student'
import { getClassList } from '@/api/class'

export default {
    name: 'StudentManage',
    components: {
        Search,
        UploadFilled
    },
    setup() {
        // 状态定义
        const studentList = ref([])
        const loading = ref(false)
        const total = ref(0)
        const dialogVisible = ref(false)
        const isEdit = ref(false)
        const studentForm = ref(null)
        const classList = ref([])

        // 查询参数
        const query = reactive({
            pageNum: 1,
            pageSize: 10,
            keyword: '',
            grade: '',
          classNumber: '',
            gender: ''
        })

        // 表单数据
        const form = reactive({
            id: null,
            studentId: '',
            name: '',
            gender: 1,
            classId: '',
            grade: '',
            createTime: ''
        })

        // 表单验证规则
        const rules = {
            studentId: [{ required: true, message: '请输入学号', trigger: 'blur' }],
            name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
            gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
            classId: [{ required: true, message: '请选择班级', trigger: 'change' }]
        }

        // 新增上传相关状态
        const uploadVisible = ref(false)
        const uploadLoading = ref(false)
        const uploadRef = ref(null)
        const fileList = ref([])
        const resultVisible = ref(false)
        const importResult = reactive({
            total: 0,
            success: 0,
            failed: 0,
            errors: []
        })

        // 新增导出相关状态
        const exportLoading = ref(false)
        const exportVisible = ref(false)
        const exportOptions = reactive({
            type: 'filtered', // current, filtered, all
            format: 'xlsx', // xlsx, csv
            fields: ['studentNumber', 'studentName', 'gender', 'className', 'grade']
        })

        // 页面加载时获取数据
        onMounted(() => {
            fetchStudentList()
            fetchClassList()
        })

        // 获取学生列表
        const fetchStudentList = async () => {
            try {
                loading.value = true
                const res = await studentApi.getStudents(query)
                console.log('获取学生列表响应:', res)
                if (res.data.code === 200) {
                    console.log('学生原始数据:', res.data.data.records)
                    // 映射后端字段到前端字段
                    studentList.value = res.data.data.records.map(item => ({
                        id: item.id,
                        studentId: item.studentNumber, // 后端字段是studentNumber，前端是studentId
                        name: item.studentName, // 后端字段是studentName，前端是name
                        gender: item.gender,
                        className: item.className.replace(/.*?((\(\d+\)|（\d+）)班)/, '$1'),
                        grade: item.grade,
                        createTime: item.createTime
                    }))
                    total.value = res.data.data.total
                } else {
                    ElMessage.error(res.data.msg || '获取学生列表失败')
                }
            } catch (error) {
                console.error('获取学生列表失败:', error)
                ElMessage.error('获取学生列表失败')
            } finally {
                loading.value = false
            }
        }

        // 获取班级列表
        const fetchClassList = async () => {
            try {
                const res = await getClassList({ current: 1, size: 1000 })
                if (res.data && res.data.records) {
                    // 只保留"x班"
                    const allClasses = res.data.records.map(item => ({
                        ...item,
                        // 保留括号，如"(2)班"
                        className: item.className.replace(/.*?((\(\d+\)|（\d+）)班)/, '$1')
                    }))
                    // 用Map去重，只保留第一个出现的className
                    const uniqueMap = new Map()
                    allClasses.forEach(item => {
                        if (!uniqueMap.has(item.className)) {
                            uniqueMap.set(item.className, item)
                        }
                    })
                    classList.value = Array.from(uniqueMap.values())
                    console.log('去重后班级列表:', classList.value)
                }
            } catch (error) {
                console.error('获取班级列表失败:', error)
            }
        }

        // 搜索
        const handleSearch = () => {
            query.pageNum = 1
            fetchStudentList()
        }

        // 分页大小变化
        const handleSizeChange = (size) => {
            query.pageSize = size
            fetchStudentList()
        }

        // 页码变化
        const handleCurrentChange = (page) => {
            query.pageNum = page
            fetchStudentList()
        }

        // 显示添加对话框
        const showAddDialog = () => {
            isEdit.value = false
            resetForm()
            dialogVisible.value = true
        }

        // 重置表单
        const resetForm = () => {
            Object.keys(form).forEach(key => {
                if (key === 'gender') {
                    form[key] = 1
                } else {
                    form[key] = ''
                }
            })
            form.id = null
        }

        // 编辑学生
        const handleEdit = async (row) => {
            try {
                console.log('编辑学生ID:', row.id)
                const res = await studentApi.getStudentById(row.id)
                console.log('获取学生详情响应:', res.data)
                if (res.data.code === 200) {
                    const student = res.data.data
                    console.log('学生详情数据:', student)
                    // 映射后端数据到表单字段
                    form.id = student.id
                    form.studentId = student.studentNumber
                    form.name = student.studentName
                    form.gender = student.gender
                    form.classId = student.classId
                    form.grade = student.grade
                    form.createTime = student.createTime

                    isEdit.value = true
                    dialogVisible.value = true
                } else {
                    ElMessage.error(res.data.msg || '获取学生详情失败')
                }
            } catch (error) {
                console.error('获取学生详情失败:', error)
                ElMessage.error('获取学生详情失败')
            }
        }

        // 删除学生
        const handleDelete = (row) => {
            ElMessageBox.confirm(`确定要删除学生 ${row.name} 吗?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try {
                    console.log('删除学生ID:', row.id)
                    const res = await studentApi.deleteStudent(row.id)
                    console.log('删除学生响应:', res.data)
                    if (res.data.code === 200) {
                        ElMessage.success('删除成功')
                        fetchStudentList()
                    } else {
                        ElMessage.error(res.data.msg || '删除失败')
                    }
                } catch (error) {
                    console.error('删除学生失败:', error)
                    ElMessage.error('删除学生失败')
                }
            }).catch(() => { })
        }

        // 提交表单
        const submitForm = async () => {
            if (!studentForm.value) return

            await studentForm.value.validate(async (valid) => {
                if (valid) {
                    try {
                        // 映射前端表单字段到后端字段
                        const studentData = {
                            id: form.id,
                            studentNumber: form.studentId,
                            studentName: form.name,
                            gender: form.gender,
                            classId: form.classId,
                            grade: form.grade
                        }

                        console.log('提交学生数据:', studentData)
                        let res
                        if (isEdit.value) {
                            // 更新学生
                            console.log('更新学生')
                            res = await studentApi.updateStudent(studentData)
                        } else {
                            // 添加学生
                            console.log('添加学生')
                            res = await studentApi.addStudent(studentData)
                        }
                        console.log('提交学生响应:', res.data)

                        if (res.data.code === 200) {
                            ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
                            dialogVisible.value = false
                            fetchStudentList()
                        } else {
                            ElMessage.error(res.data.msg || (isEdit.value ? '更新失败' : '添加失败'))
                        }
                    } catch (error) {
                        console.error(isEdit.value ? '更新学生失败:' : '添加学生失败:', error)
                        ElMessage.error(isEdit.value ? '更新学生失败' : '添加学生失败')
                    }
                }
            })
        }

        // 显示上传对话框
        const showUploadDialog = () => {
            uploadVisible.value = true
            fileList.value = []
        }

        // 处理文件超出限制
        const handleExceed = (files) => {
            ElMessage.warning('只能上传一个文件')
        }

        // 上传前检查
        const beforeUpload = (file) => {
            const isXlsx = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
            const isLt10M = file.size / 1024 / 1024 < 10;
            if (!isXlsx) {
                ElMessage.error('只能上传Excel（.xlsx）文件!');
                return false;
            }
            if (!isLt10M) {
                ElMessage.error('上传文件大小不能超过10MB!');
                return false;
            }
            return true;
        }

        // 提交上传
        const submitUpload = async () => {
            if (fileList.value.length === 0) {
                ElMessage.warning('请先选择文件')
                return
            }

            const file = fileList.value[0].raw
            const formData = new FormData()
            formData.append('file', file)

            uploadLoading.value = true
            try {
                const res = await studentApi.importStudents(formData)
                if (res.data.code === 200) {
                    ElMessage.success('导入完成')
                    uploadVisible.value = false

                    // 显示导入结果
                    importResult.total = res.data.data.total
                    importResult.success = res.data.data.success
                    importResult.failed = res.data.data.failed
                    importResult.errors = res.data.data.errors || []
                    resultVisible.value = true

                    // 刷新列表
                    fetchStudentList()
                } else {
                    ElMessage.error(res.data.msg || '导入失败')
                }
            } catch (error) {
                console.error('导入失败:', error)
                ElMessage.error('导入失败')
            } finally {
                uploadLoading.value = false
            }
        }

        // 导出学生数据
        const handleExport = () => {
            showExportDialog()
        }

        // 显示导出对话框
        const showExportDialog = () => {
            exportVisible.value = true
        }

        // 确认导出
        const confirmExport = async () => {
            try {
                exportLoading.value = true;
                const exportParams = {
                    ...exportOptions,
                    query: exportOptions.type === 'all' ? {} : query
                };
                const res = await studentApi.exportStudents(exportParams);

                if (res.data) {
                    const blob = new Blob([res.data], {
                        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                    });
                    const url = window.URL.createObjectURL(blob);
                    const link = document.createElement('a');
                    link.href = url;
                    link.download = `学生数据_${new Date().toISOString().slice(0, 10)}.xlsx`;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    window.URL.revokeObjectURL(url);
                    exportVisible.value = false;
                    ElMessage.success('导出成功');
                } else {
                    ElMessage.error('导出失败');
                }
            } catch (error) {
                console.error('导出失败:', error);
                ElMessage.error('导出失败');
            } finally {
                exportLoading.value = false;
            }
        };

        const resetQuery = () => {
            query.keyword = ''
            query.grade = ''
            query.classId = ''
            query.gender = ''
            fetchStudentList()
        }

        return {
            studentList,
            loading,
            total,
            dialogVisible,
            isEdit,
            studentForm,
            classList,
            query,
            form,
            rules,
            handleSearch,
            handleSizeChange,
            handleCurrentChange,
            showAddDialog,
            handleEdit,
            handleDelete,
            submitForm,
            uploadVisible,
            uploadLoading,
            uploadRef,
            fileList,
            resultVisible,
            importResult,
            showUploadDialog,
            handleExceed,
            beforeUpload,
            submitUpload,
            exportLoading,
            handleExport,
            exportVisible,
            exportOptions,
            showExportDialog,
            confirmExport,
            resetQuery
        }
    }
}
</script>

<style>
.student-manage {
    padding: 20px;
}

.actions {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
}

.table-container {
    max-height: 500px;
    overflow-y: auto;
    background: #fff;
    border-radius: 4px;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.upload-tips {
    margin-bottom: 20px;
    padding: 15px;
    background-color: #f0f9ff;
    border-radius: 4px;
}

.upload-tips p {
    margin: 0 0 10px 0;
    color: #666;
}

.upload-tips p:last-child {
    margin-bottom: 0;
}

.upload-demo {
    width: 100%;
}

.result-summary {
    margin-bottom: 20px;
}

.error-details {
    margin-top: 20px;
}

.error-details h4 {
    margin-bottom: 10px;
    color: #f56565;
}
</style>
